$(document).ready(function () {
    $(".pick-content").on("input propertychange",function () {
        console.log($(this).val(),'kkkk');
        var q = $(this).val();
        $("#movie-list").empty();
        $.get("/search/datatip/",{'q':q},function (data) {
                $.each(JSON.parse(data),function (index,value) {
                    $("#movie-list").append('<option value="'+value.fields.title+'"></option>');
                })
        })
    });
    $(".pick-movie").click(function () {

        var pick_content = $(".pick-content").val();
        if (pick_content.length <= 0) {
            alert("不许空");
            return false;
        }
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/search/",
            data: {'key': pick_content},
            success: function (data) {
                $('.row').empty();
                $.each(data, function (index, value) {
                        var movieVal = '<div class="col-sm-6 col-md-4 sudoku">' +
                            '<div class="thumbnail">'
                            + '<img src=" ' + value.fields.image + '" ' + 'alt="...">'
                            + '<div class="caption">'
                            + '<p><a href="' + '/movie_info/' + value.pk + '/"' + ' class="btn btn-primary" role="button">详情</a>'
                            + '<p><span>片名:' + value.fields.title + '</span></p>'
                            + '<p>主演</p>' + ParseCasts(value.fields.casts) + '</div></div>';
                        $('.row').append(movieVal);
                    }
                )
            }
        });
    });
    $("#select1 dd").click(function () {
        $(this).addClass("selected").siblings().removeClass("selected");
        if ($(this).hasClass("select-all")) {
            $("#selectA").remove();
        } else {
            var copyThisA = $(this).clone();
            if ($("#selectA").length > 0) {
                $("#selectA a").html($(this).text());
            } else {
                $(".select-result dl").append(copyThisA.attr("id", "selectA"));
            }
        }
    });
    //REW： 动态元素添加的范例
    $("#select2 dd").click(function () {
        $(this).addClass("selected").siblings().removeClass("selected");
        if ($(this).hasClass("select-all")) {
            $("#selectB").remove();
        } else {
            var copyThisB = $(this).clone();
            if ($("#selectB").length > 0) {
                $("#selectB a").html($(this).text());
            } else {
                $(".select-result dl").append(copyThisB.attr("id", "selectB"));
            }
        }
    });

    $("#select3 dd").click(function () {
        $(this).addClass("selected").siblings().removeClass("selected");
        if ($(this).hasClass("select-all")) {
            $("#selectC").remove();
        } else {
            var copyThisC = $(this).clone();
            if ($("#selectC").length > 0) {
                $("#selectC a").html($(this).text());
            } else {
                $(".select-result dl").append(copyThisC.attr("id", "selectC"));
            }
        }
    });

    $(".select").on("click", "#selectA", function () {
        alert("selectA");
        $(this).remove();
        $("#select1 .select-all").addClass("selected").siblings().removeClass("selected");
    });

    $(".select").on("click", "#selectB", function () {
        $(this).remove();
        $("#select2 .select-all").addClass("selected").siblings().removeClass("selected");
    });

    $(".select").on("click", "#selectC", function () {
        $(this).remove();
        $("#select3 .select-all").addClass("selected").siblings().removeClass("selected");
    });

    $(".select").on("click", "dd", function () {
        if ($(".select-result dd").length > 1) {
            $(".select-no").hide();
            $("#select-submit").show();
        } else {
            $(".select-no").show();
            $("#select-submit").hide();
        }
    });

    $("#select-submit").click(function () {
        var empty = "";
        // REW: text() val() html()的获取值的区别
        var genre = $("#selectA a").text();
        var area = $("#selectB a").text();// 选择元素的纯文本
        var year_begin = $("#year-one").val();// input类型里的值
        var year_end = $("#year-two").val();
        empty += area;
        var urlstate = '';
        if (YearVerify(year_begin, year_end)) {
            urlstate += year_begin + "-" + year_end;
        }
        $.ajax({
                // context:
                dataType: 'json',// 返回数据将自动以json解析化
                url: '/search/',
                data: {'genre': genre, 'area': area, 'year': urlstate},// get时自动附加到url后
                type: "GET",
                // async: false,
                success: function (data) {
                    $('.row').empty();
                    $('.paginator').empty();
                    var currentPage = 1;
                    console.log(',,,,',data.length);
                    // var options = {
                    //     currentPage: currentPage,
                    //     totalPage: data.length,
                    //     numberOfPages: 4,
                    //     bootstrapMajorVersion: 3,//如果是bootstrap3版本需要加此标识，并且设置包含分页内容的DOM元素为UL,如果是bootstrap2版本，则DOM包含元素是DIV
                    //     useBootstrapTooltip: false,//是否显示tip提示框
                    //     itemTexts: function (type, page, current) {
                    //         switch (type) {
                    //             case "first":
                    //                 return "首页";
                    //             case "prev":
                    //                 return "上一页";
                    //             case "next":
                    //                 return "下一页";
                    //             case "last":
                    //                 return "尾页";
                    //             case "page":
                    //                 return page;
                    //         }
                    //     },
                    //     onPageClicked: function (event, originalEvent, type, page) {
                    //         $.ajax({
                    //             url: '/getData?CurrentPage=' + page, //点击分页提交当前页码
                    //             success: function (data) {
                    //                 if (data != null) {
                    //                     //DOM操作
                    //                 }
                    //             }
                    //         })
                    //
                    //     }
                    // };
                    $.each(data, function (index, value) {
                        // console.log("value" + value.fields.title);
                        var movieVal = '<div class="col-sm-6 col-md-4 sudoku">'+
                            '<div class="thumbnail">'
                            + '<img src=" ' + value.fields.image + '" ' + 'alt="...">'
                            + '<div class="caption">'
                            + '<p><a href="' + '/movie_info/' + value.pk + '/"' + ' class="btn btn-primary" role="button">详情</a>'
                            + '<p><span>片名:' + value.fields.title + '</span></p>'
                            + '<p>主演</p>' + ParseCasts(value.fields.casts) + '</div></div></div>';
                        $('.row').append(movieVal);
                    });
                    // $(".paginator").bootstrapPaginator(options);
                }
            }
        )
    });
    // $(".filtrate-sort").on('click',".filter-sort", function () {
    //     var sort_way = $(this).attr("data-sort");
    //     alert(sort_way);
    //     $.ajax({
    //         type: "get",
    //         url: "/1",
    //         data: {"sort":sort_way},
    //         success: function () {
    //             window.location.href="/1/?sort=comments"
    //         },
    //         fail: function () {
    //             alert('fail')
    //         }
    //     })
    // })
});

/**
 * @return {boolean}
 */
function YearVerify(year_begin, year_end) {
    return !!(year_begin && year_end);
}

/**
 * @return {string}
 */
function ParseCasts(casts) {
    castsString = '';
    castss = casts.split(",");
    if (castss instanceof Array) {
        castss.forEach(function (value, index, array) {
            csts = '<li>' + value + '</li>';
            castsString += csts;
        });
    } else {
        castsString = "<li>" + castss + "</li>"
    }
    return castsString;
}

function search(inputID, datalistID, itemName) {
    var pick_content = document.getElementById(inputID);
    var datalist = document.getElementById(datalistID);
    if (pick_content.value.length === 0 || pick_content.value === " ") {
        var sub = datalist.childNodes;
        if (sub.length > 0) {
            for (var i = 0; i < sub.length; i++) {
                datalist.removeChild(sub[i])
            }
        }
        listobj = null;
        requestItem = null;
        inputContent.value = null;
        return false
    }
    listobj = datalist;
    requestItem = itemName;
    var data = "";
    var url = "";
    if (/^[a-zA-Z]*$/.test(inputContent.value)) {
        //检测出是拼音首字母
        data = "type=searchWords¶m=" + inputContent.value;      //注意：data-----------需要自定义
        url = baseurl + "/servlet/ListDemo";                      //注意：url-----------需要自定义
        sendRequest("post", url, data, getResult);
    }
    else if (/^[\u4e00-\u9fa5]*$/.test(inputContent.value)) {
        //检测出是中文
        data = "type=searchChinese¶m=" + inputContent.value;    //注意：data-----------需要自定义
        url = baseurl + "/servlet/ListDemo";                      //注意：url-----------需要自定义
        sendRequest("post", url, data, getResult);
    }
}

function getResult(result) {
    var data = reslut;
    var JData = eval("(" + data + ")");
    var maxlength = 10;              //注释：maxlength保证过多查询结果下只显示10条
    if (JData.length <= 10) {
        maxlength = JData.length;
    }
    var sub = listobj.childNodes;
    for (var i = sub.length - 1; i >= 0; i--) {
        listobj.removeChild(sub[i]);    //清空datalist所有的下拉选项
    }
    if (JData.length === 0)  //没有查询结果
    {
        alert("没有符合条件的结果，请重输");
        inputContent.value = "";    //清空input输入框的值
        return false;
    }
    for (var i = 0; i < maxlength; i++) {
        var obj = document.createElement("option");
        var indexobj = JData[i];
        if (/^[a-zA-Z]*$/.test(inputContent.value)) {
            obj.value = indexobj[requestItem];
            obj.innerHTML = inputContent.value;
        }
        if (/^[\u4e00-\u9fa5]*$/.test(inputContent.value)) {
            obj.value = indexobj[requestItem];
        }
        listobj.appendChild(obj);
    }
    var suffix = document.createElement("option");
    suffix.value = " ";
    suffix.innerHTML = "输入更多有关" + inputContent.value + "的信息";
    listobj.appendChild(suffix);
}